package com.deeper.customview.ui.c2.demo.c02d05;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import com.deeper.customview.R;

public class ClipView extends View {
    private Bitmap boomBmp;
    private int i = 0;//显示第i张小图片


    public ClipView(Context context) {
        super(context);
    }


    public ClipView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        boomBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.boom);
    }


    public ClipView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        //获取位置的宽度和高度
        int width = boomBmp.getWidth();
        int height = boomBmp.getHeight();
        //剪切区
        int frameWidth = width / 5;
        Rect rect = new Rect(0, 0, frameWidth, height);

        canvas.save();
        canvas.translate(100, 100);//平移坐标
        canvas.clipRect(rect);//设置剪切区
        canvas.drawBitmap(boomBmp, -i * frameWidth, 0, null);
        canvas.restore();

        i++;
        if (i == 5) i = 0;//播放完毕后将i重置为0重新播放
    }
}
